package com.lty.jeeg.server.modules.fas.service.impl;

import com.google.common.collect.Lists;
import com.lty.jeeg.server.common.enums.ResponseEnum;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.common.utils.UserUtil;
import com.lty.jeeg.server.modules.fas.dao.OrderDetailDao;
import com.lty.jeeg.server.modules.fas.dto.OrderDTO;
import com.lty.jeeg.server.modules.fas.export.OrderExportEntity;
import com.lty.jeeg.server.modules.fas.model.OrderDetail;
import com.lty.jeeg.server.modules.sys.dao.FileInfoDao;
import com.lty.jeeg.server.modules.sys.model.FileInfo;
import com.lty.jeeg.server.modules.sys.model.User;
import com.lty.jeeg.server.modules.sys.service.impl.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lty.jeeg.server.modules.fas.dao.OrderDao;
import com.lty.jeeg.server.modules.fas.model.Order;
import com.lty.jeeg.server.modules.fas.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author : ZL
 * @date : 2019-02-13 10:41:32
 * Description : 需求单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderDao orderDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    public OrderServiceImpl(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    @Autowired
    private FileInfoDao fileInfoDao;

    @Override
    public OrderDTO getById(Long id) {
        Order order = orderDao.getById(id);
        OrderDTO orderDTO = BeanConverter.map(order, OrderDTO.class);
        String screenshotPath = orderDTO.getScreenshotPath();
        if (StringUtils.isNotEmpty(screenshotPath)) {
            List<FileInfo> screenshots = Lists.newArrayList();
            String[] screenshotArray = screenshotPath.substring(1).split("\\|");
            for (String fileId: screenshotArray) {
                screenshots.add(fileInfoDao.getById(fileId));
            }
            orderDTO.setScreenshotPaths(screenshots);
        }
        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.debug("删除Order=>{}", id);
        return orderDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Order order) {
        User user = UserUtil.getCurrentUser();
            order.preUpdate();
            List<OrderDetail> orderDetailList = order.getOrderDetailList();
            if (orderDetailList != null && orderDetailList.size() > 0) {
                for (OrderDetail orderDetail : orderDetailList) {
                    if (orderDetail != null) {
                        if (order.getIsDeleted().equals(0)) {
                            orderDetail.preUpdate();
                            orderDetail.setWaitNum(orderDetail.getDetailNum().intValue());
                            orderDetailDao.update(orderDetail);
                        } else {
                            //删除
                            //orderDetailDao.delete(orderDetail.getId());
                        }
                    }
                }
            }
            log.debug("修改Order=>{}", order.getId());
            return orderDao.update(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(Order order) {
        order.preInsert();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String newName = "XQ" + date + new Random().nextInt(10000);
        order.setName(newName);
        order.setOrderType(0);
        orderDao.save(order);
        List<OrderDetail> orderDetailList = order.getOrderDetailList();
        if (orderDetailList != null && orderDetailList.size() > 0) {
            for (OrderDetail orderDetail : orderDetailList) {
                if (orderDetail != null) {
                    if (order.getIsDeleted().equals(0)) {
                        String orderDetailName = "MX" + date + new Random().nextInt(10000);
                        orderDetail.setName(orderDetailName);
                        orderDetail.setOrderId(order.getId());
                        if (order.getOriginatorId() != null) {
                            orderDetail.setOriginatorId(order.getOriginatorId());
                        }
                        orderDetail.setOriginatorName(order.getOriginatorName());
                        orderDetail.setOriginatorOfficeId(order.getOriginatorOfficeId());
                        orderDetail.setOriginatorOfficeName(order.getOriginatorOfficeName());
                        orderDetail.setCompanyId(order.getCompanyId());
                        orderDetail.preInsert();
                        orderDetail.setWishPayDate(order.getWishPayDate());
                        orderDetail.setIsDeleted(0);
                        orderDetail.setOrderType(order.getOrderType());
                        orderDetail.setHandleType(0);//本条明细交付状态----（未使用）
                        orderDetail.setActNum(0); //已交付数量为空
                        orderDetail.setBuyStatus(0);
                        orderDetail.setOrderDetailType(0);    //订单明细变更为待提交状态
                        orderDetail.setWaitNum(orderDetail.getDetailNum().intValue());    //待交付默认为需求数量
                        orderDetailDao.save(orderDetail);
                    } else {
                        //删除
                        orderDetailDao.delete(orderDetail.getId());
                    }
                }
            }
        }
        log.debug("新增Order=>{}", order.getId());
        return order.getId();
    }

    @Override
    public PageTableResponse list(PageTableRequest request) {
        request.getParams().put("dsf", BaseService.dataScopeFilter("fas", UserUtil.getCurrentUser(), "du", "ua"));
        return new PageTableHandler(
                request1 -> orderDao.count(request1.getParams()),
                request2 -> orderDao.list(
                        request2.getParams(), request2.getOffset(), request2.getLimit()))
                .handle(request);
    }

    @Override
    public int changeType(Long id, String type) {
        return orderDao.changeType(id, type);
    }

    /**
     * 导出需求单数据
     *
     * @param orderDTO
     * @return
     */
    @Override
    public List<OrderExportEntity> getExportDatas(OrderDTO orderDTO) {
        return orderDao.getExportDatas(orderDTO);
    }


}
